(function ($) {
  Drupal.behaviors.shushengyuanlueQrLoginForm = {
    attach: function (context) {

      let countdown = 60;
      qr();
      setInterval(function () {
        countdown--;
        if (countdown <= 0) {
          qr();
          countdown = 60;
        }
        $("#countdownBox").text(countdown);
      }, 1000);

      //长连接监听扫码状态
      function login(qr) {
        let date = new Date();
        let url = `/user/qr-login/callback/${qr}?` + date.getTime();
        $.get(url, {}, function (res) {
              if (res.code === 1) {
                login(qr);
              }
              else if (res.code === 0) {
                window.location.href = "/";
              }
            },
            "json",
        );
      }

      function qr() {
        let date = new Date();
        let url = "/user/qr-login/qr?" + date.getTime();
        $.get(url, {}, function (res) {
              if (res.code === 0) {
                $("#qrBox").attr("src", res.url);
                login(res.qr);
              }
              else {
                alert(res.message);
              }
            },
            "json",
        );
      }
    },
  };
})(jQuery);
